package com.cn.shuangzi.ad.activity;


import android.os.Handler;
import android.view.View;

import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.activity.SZSplashActivity;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.ADPlatform;
import com.cn.shuangzi.ad.bean.KsErrorInfo;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.manager.AdSplashManager;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.tt.SplashShownManager;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.kwad.sdk.api.KsSplashScreenAd;
import com.qq.e.ads.splash.SplashAD;

import java.util.List;

/**
 * 开屏广告Activity示例
 */
public abstract class GroMoreSplashActivity extends SZSplashActivity {

    private String mAdUnitId = "";
    private AdSplashManager mAdSplashManager;
    private boolean isAdShown;
    private int SPLASH_SHOW_TIME_NORMAL = 1500;
    private long beginTime;
    private Handler handlerCloseSplashNoAd;
    private Handler handlerCloseSplashHasAd;
    private boolean isDealToNext = false;
    private boolean isForceClose;
    private boolean isClickAd;

    @Override
    public void onPreCreated() {
        isForceClose = false;
        isClickAd = false;
        resetSplashManager();
        initCutDown();
    }

    public void init(boolean isShowAd) {
        init(isShowAd, 1000);
    }

    public void init(boolean isShowAd, long delayToMain) {
        SZApp.getInstance().init();
        dealAd(isShowAd, delayToMain);
    }

    public void dealAd(boolean isShowAd) {
        dealAd(isShowAd, 1000);
    }

    public void dealAd(boolean isShowAd, long delayToMain) {
        if (isShowAd) {
            autoCloseSplash();
            ADUtil.logError("设置自动关闭成功");
            fetchSplashAD();
        } else {
            ADUtil.logError("不展示广告，直接进主页");
            toMain(delayToMain);
        }
    }
    private void resetSplashManager(){
        SplashShownManager.getInstance().setSplashShown(false);
    }


    public void fetchSelfAD() {
        fetchSelfAD(null);
    }

    public void fetchSelfAD(ADManager.OnSplashADLoadListener onSplashADLoadListener) {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(ADUtil.getChannel(this), getPackageName(), String.valueOf(ADUtil.getVersionCode()), onSplashADLoadListener);
    }

    private void fetchSplashAD() {

        beginTime = System.currentTimeMillis();
        mAdUnitId = getAdUnitId();

        initAdLoader();
        resetSplashManager();
        ADManager.getInstance().getSplash(ADUtil.getChannel(this), getPackageName(), String.valueOf(ADUtil.getVersionCode()), new ADManager.OnSplashADLoadListener() {
            @Override
            public void onFetchAdSuccess(List<ADPlatform> adPlatformList) {
                if(SZValidatorUtil.isValidList(adPlatformList)) {
                    if (mAdSplashManager != null) {
                        mAdSplashManager.loadAd(mAdUnitId, isFullScreenMode() ? 0 : rltBottom.getHeight(),getBottomAdCodeId(),getScenarioId());
                    }
                }else{
                    toMainByDelay(false);
                }
            }

            @Override
            public void onFetchAdError() {
                toMainByDelay(false);
            }
        });

    }
    private void initCutDown() {
        txtVipSkip.setVisibility(View.GONE);
        txtVipSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    startActivity(getVipActivity());
                    isClickAd = true;
                    try {
                        if(handlerCloseSplashHasAd!=null){
                            handlerCloseSplashHasAd.removeCallbacksAndMessages(null);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                }
            }
        });
        txtSkip.setVisibility(View.GONE);
        txtSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toMainByDelay(true);
            }
        });
    }

    private void showCutDown() {
        try {
            if(handlerCloseSplashNoAd!=null){
                handlerCloseSplashNoAd.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            autoCloseSplashHasAd();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        if (isShowVipSkipBtn()) {
            txtVipSkip.setVisibility(View.VISIBLE);
        } else {
            txtVipSkip.setVisibility(View.GONE);
        }
        if(isShowSkipBtn()){
            txtSkip.setVisibility(View.VISIBLE);
        }else {
            txtSkip.setVisibility(View.GONE);
        }
    }

    public void autoCloseSplash() {
        //未知情况出现卡死的情况下，主动执行跳转
        //未显示广告自动跳转逻辑
        try {
            if(handlerCloseSplashNoAd!=null){
                handlerCloseSplashNoAd.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplashNoAd = new Handler();
        handlerCloseSplashNoAd.postDelayed(new Runnable() {
            @Override
            public void run() {
                ADUtil.logError("是否需要自动关闭："+!isAdShown);
                if (!isAdShown) {
                    if (!isFinishing()) {
                        ADUtil.logError("=====没有显示广告，执行的自动关闭=====");
                        toMain();
                    }
                }
            }
        }, getSplashCloseDelayTimeInNoAd());
    }

    public void autoCloseSplashHasAd(){
        ADUtil.logError("显示广告后，设置自动关闭成功");
        //已显示广告自动跳转逻辑
        try {
            if(handlerCloseSplashHasAd!=null){
                handlerCloseSplashHasAd.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplashHasAd = new Handler();
        handlerCloseSplashHasAd.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isFinishing()) {
                    ADUtil.logError("=====已有广告，执行的自动关闭=====");
                    toMain();
                }
            }
        }, getSplashCloseDelayTimeInHasAd());
    }
    private int getReportEcmp(int lossEcpm, String winEcpm){
        int ecpm = lossEcpm;
        try {
            if(ecpm<=0){
                ecpm = 20 * ADConst.YUAN;
            }
            double preEcpm = Double.parseDouble(winEcpm);
            if(preEcpm>0) {
                int addCPM = ADUtil.getRandom(4*ADConst.YUAN,2*ADConst.YUAN);
                ecpm = (int) (preEcpm + addCPM);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ecpm;
    }

    private void initAdLoader() {
        mAdSplashManager = new AdSplashManager(this, new TTAdNative.CSJSplashAdListener() {
            @Override
            public void onSplashLoadSuccess(CSJSplashAd csjSplashAd) {

                ADUtil.logError("====聚合开屏加载成功====");
                csjSplashAd.setSplashAdListener(new CSJSplashAd.SplashAdListener() {
                    @Override
                    public void onSplashAdShow(CSJSplashAd csjSplashAd) {
                        ADUtil.setFirstUseAdTime();
                        ADUtil.logError("=======开屏广告显示onSplashAdShow========");
                        isAdShown = true;
                        if (isFullScreenMode()) {
                            rltBottom.setVisibility(View.GONE);
                        } else {
                            rltBottom.setVisibility(View.VISIBLE);
                        }
                        showCutDown();
                        MediationAdEcpmInfo gmAdEcpmInfo = null;
                        try {
                            gmAdEcpmInfo = mAdSplashManager.getSplashAd().getMediationManager().getShowEcpm();
                            ADUtil.logError("当前开屏SdkName："+gmAdEcpmInfo.getSdkName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getSplashYlhErrorInfo();
                        SplashAD ylhSplashAD = ADManager.getInstance().getYlhSplashAD();
                        KsErrorInfo ksErrorInfo = ADManager.getInstance().getSplashKsErrorInfo();
                        KsSplashScreenAd ksSplashAD = ADManager.getInstance().getKsSplashAd();
                        if(gmAdEcpmInfo!=null){
                            if(ylhErrorInfo!=null&&ylhSplashAD!=null&&
                                    !ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getSdkName())){
                                int ecpm = getReportEcmp(ylhSplashAD.getECPM(),gmAdEcpmInfo.getEcpm());
                                ylhSplashAD.sendLossNotification(ecpm,ylhErrorInfo.getReason(),ylhErrorInfo.getAdnId());
                                ADUtil.logError("上报优量汇开屏竞价失败：ecpm="+ecpm+"，"+ylhErrorInfo);
                            }
                            if(ksErrorInfo!=null&&ksSplashAD!=null&&
                                    !ADManager.getInstance().isKsPlatform(gmAdEcpmInfo.getSdkName())){
                                if(ksErrorInfo.getAdExposureFailedReason()!=null){
                                    ksErrorInfo.getAdExposureFailedReason().setWinEcpm(getReportEcmp(ksSplashAD.getECPM(),gmAdEcpmInfo.getEcpm()))
                                            .setAdnName(ADManager.getInstance().getReportKsAdnName(gmAdEcpmInfo.getSdkName()));
                                }
                                ksSplashAD.reportAdExposureFailed(ksErrorInfo.getAdExposureFailureCode(),ksErrorInfo.getAdExposureFailedReason());
                                ADUtil.logError("上报快手开屏竞价失败："+ksErrorInfo);
                            }
                        }
                        ADManager.getInstance().clearCurrentSplash();
                    }

                    @Override
                    public void onSplashAdClick(CSJSplashAd csjSplashAd) {
                        ADUtil.logError("开屏广告被点击");
                        isClickAd = true;
                        try {
                            if(handlerCloseSplashHasAd!=null){
                                handlerCloseSplashHasAd.removeCallbacksAndMessages(null);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onSplashAdClose(CSJSplashAd csjSplashAd, int i) {
                        ADUtil.logError("=========开屏广告关闭onSplashAdClose==========");
                        toNext();
                    }
                });
                mAdSplashManager.showSplashAd(splash_container,csjSplashAd);
                SplashShownManager.getInstance().setSplashShown(true);
                mAdSplashManager.printInfo();

            }

            @Override
            public void onSplashLoadFail(CSJAdError csjAdError) {

                ADUtil.logError("聚合开屏加载失败 : " + csjAdError.getCode() + ", " + csjAdError.getMsg());
                // 获取本次waterfall加载中，加载失败的adn错误信息。
                if (mAdSplashManager.getSplashAd() != null) {
                    try {
                        ADUtil.logError("聚合开屏加载失败数据: " + mAdSplashManager.getSplashAd().getMediationManager().getAdLoadInfo());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                toMainByDelay(false);
            }

            @Override
            public void onSplashRenderSuccess(CSJSplashAd csjSplashAd) {

                ADUtil.logError("=======开屏广告onSplashRenderSuccess========");
            }

            @Override
            public void onSplashRenderFail(CSJSplashAd csjSplashAd, CSJAdError csjAdError) {

                ADUtil.logError("聚合开屏展示失败 : " + csjAdError.getCode() + ", " + csjAdError.getMsg());
                // 获取本次waterfall加载中，加载失败的adn错误信息。
                if (mAdSplashManager.getSplashAd() != null) {
                    try {
                        ADUtil.logError("聚合开屏展示失败数据: " + mAdSplashManager.getSplashAd().getMediationManager().getAdLoadInfo());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                toMainByDelay(false);
            }

        });
    }

    private void toNext() {
        if (!isDealToNext) {
            next();
        }
        isDealToNext = true;
    }

    private void toMainByDelay(boolean isNowSkip) {
        if (isNowSkip) {
            ADUtil.logError("=====执行立即跳转=====");
            toMain();
        } else {
            long delay = getDelayFinishTime();
            ADUtil.logError("=====执行延时跳转====="+delay);
            toMain(delay);
        }
    }

    private long getDelayFinishTime() {
        long errorTime = System.currentTimeMillis();
        long remainderTime = SPLASH_SHOW_TIME_NORMAL - (errorTime - beginTime);
        return remainderTime > 0 ? remainderTime : 0;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isForceClose = true;
    }

    @Override
    protected void onResume() {
        if(isForceClose&&isClickAd){
            toMain();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAdSplashManager != null) {
            mAdSplashManager.destroy();
        }
        try {
            if (handlerCloseSplashNoAd != null) {
                handlerCloseSplashNoAd.removeCallbacksAndMessages(null);
            }
            if (handlerCloseSplashHasAd != null) {
                handlerCloseSplashHasAd.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplashNoAd = null;
        handlerCloseSplashHasAd = null;
    }

    public long getSplashCloseDelayTimeInNoAd() {
        return 6000;
    }

    public long getSplashCloseDelayTimeInHasAd(){
        return 11*1000;
    };
    protected String getScenarioId() {
        return null;
    }

    public abstract String getAdUnitId();

    public abstract String getBottomAdCodeId();

    public abstract boolean isFullScreenMode();

    public abstract boolean isShowVipSkipBtn();

    public abstract Class<?> getVipActivity();

    protected abstract boolean isShowSkipBtn();
}
